<template>
  <a-modal
    width="70%"
    v-model:visible="visible"
    @cancel="onCancel"
    @before-ok="onOk"
    :esc-to-close="false"
  >
    <template #title>
      <div class="w-full">
        <span class="font-bold">{{
          `【${groupInfo?.nickname ?? ''}】请设置要跟发的群成员（可多选）（${tableData.length}）`
        }}</span>
      </div>
    </template>
    <div class="flex flex-a-c w-full mb-20">
      <a-input-search
        allow-clear
        size="large"
        placeholder="输入群成员名称检索"
        v-model="searchValue"
      />
    </div>
    <a-checkbox-group class="w-full" v-model="memberIds">
      <a-table
        :columns="columns"
        :data="tableData"
        :show-header="false"
        row-key="Wxid"
        :bordered="false"
        :pagination="false"
        :loading="loading"
        :scroll="{ y: 400 }"
      >
        <template #memberInfo="{ rowIndex, record }">
          <div class="flex flex-a-c">
            <!-- <div class="w-30 mr-20 flex flex-j-c">{{ rowIndex + 1 }}</div> -->
            <a-image
              width="42"
              height="42"
              class="mx-4"
              :preview="false"
              style="border-radius: 4px"
              :src="record.avatar"
            />
            <span class="ml-16">{{ record.nickname }}</span>
          </div>
        </template>
        <template #action="{ record }">
          <div class="flex flex-a-c flex-j-e" v-if="groupInfo">
            <a-checkbox
              :value="`${groupInfo.wxid}❤${record.wxid}`"
              :disabled="weixinInfo.wxid === record.wxid"
            >
              <template #checkbox="{ checked }">
                <a-space
                  align="start"
                  class="custom-radio-card"
                  :class="{ 'custom-radio-card-checked': checked }"
                >
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot" />
                  </div>
                  <div>
                    <div className="custom-radio-card-title">选择</div>
                  </div>
                </a-space>
              </template>
            </a-checkbox>
          </div>
        </template>
      </a-table>
    </a-checkbox-group>
  </a-modal>
</template>

<script setup>
import { Message } from '@arco-design/web-vue'
const { ipcRenderer } = window.electron
const emit = defineEmits(['handleRegression', 'handleChooseMember'])
const visible = ref(false)
const loading = ref(false)
const searchValue = ref()
const tableDataO = reactive([])
const weixinInfo = ref()
const memberLength = ref(0)
const groupInfo = ref()
const memberIds = ref([])
let selectedId = null
const compere = ref([])
const isIndex = ref(false)
const columns = [
  {
    title: '群成员',
    slotName: 'memberInfo',
    width: 100
  },
  {
    title: '操作',
    slotName: 'action',
    width: 50
  }
]

onMounted(async () => {
  weixinInfo.value = await window.ipcRenderer.invoke('storeGet', 'weixinInfo')
})

const tableData = computed(() => {
  if (searchValue.value) {
    return tableDataO.filter((item) => item.nickname.includes(searchValue.value))
  } else {
    return tableDataO.slice() // 使用 slice() 创建 tableDataO 的浅拷贝
  }
})

// 监听群成员列表消息
ipcRenderer.on('recvWxGroupMember', async (event, message) => {
  const memberList = message?.member_list ?? []
  // 使用 Set 来提高成员 ID 的检索效率
  const memberIdsSet = new Set(memberIds.value)
  // 分离满足条件和不满足条件的数据
  const filteredMessages = {
    included: [],
    excluded: []
  }
  for (const item of memberList) {
    if (memberIdsSet.has(`${groupInfo.value?.wxid}❤${item.wxid}`)) {
      filteredMessages.included.push(item)
    } else {
      filteredMessages.excluded.push(item)
    }
  }
  // 将满足条件的数据放置在前部
  if (filteredMessages.included.length > 0) {
    tableDataO.splice(
      0,
      tableDataO.length,
      ...filteredMessages.included,
      ...filteredMessages.excluded
    )
  } else {
    tableDataO.splice(0, tableDataO.length, ...memberList) // 如果没有满足条件的数据，直接复制整个 message 数组
  }
  memberLength.value = tableDataO.length
  if (loading.value) {
    loading.value = false
  }
})

// 打开编辑框并回显表单值
const openMemberModal = (itemO, selectedIdO, compereO) => {
  visible.value = true
  loading.value = true
  isIndex.value = false
  selectedId = selectedIdO
  compere.value = compereO
  // 如果是回显的情况，需要手动回显已选择的成员
  if (itemO.wxid == selectedId && compereO.length && !memberIds.value.length) {
    const res = []
    compereO.forEach((item) => {
      res.push(`${selectedId}❤${item.wxid}`)
    })
    memberIds.value = res
  }
  if (groupInfo.value && groupInfo.value.wxid === itemO.wxid && tableData.value.length)
    return (loading.value = false)
  groupInfo.value = itemO
  ipcRenderer.send('getWxGroupMember', itemO.wxid)
  setTimeout(() => {
    if (loading.value) loading.value = false
  }, 3000)
}

// 从首页直接打开换选择框
const openMemberModal2 = (itemO) => {
  visible.value = true
  loading.value = true
  isIndex.value = true
  if (itemO?.fllowSetting?.Member.length) {
    const res = []
    itemO.fllowSetting.Member.forEach((item) => {
      res.push(`${itemO.fllowSetting.wxid}❤${item.wxid}`)
    })
    memberIds.value = res
  }
  if (groupInfo.value && groupInfo.value.wxid === itemO.fllowSetting.wxid && tableData.value.length)
    return (loading.value = false)
  groupInfo.value = itemO.fllowSetting
  ipcRenderer.send('getWxGroupMember', itemO.fllowSetting.wxid)
  setTimeout(() => {
    if (loading.value) loading.value = false
  }, 3000)
}

// 点击取消
const onCancel = () => {
  if (isIndex.value) return
  // 如果点击取消，并且之前选择的有值，则手动还原
  if (selectedId && compere.value.length) {
    const res = []
    compere.value.forEach((item) => {
      res.push(`${selectedId}❤${item.wxid}`)
    })
    memberIds.value = res
  }
  emit('handleRegression')
}

// 点击确认添加/编辑
const onOk = async () => {
  const result = tableData.value.filter((item) => {
    return memberIds.value.includes(`${groupInfo.value.wxid}❤${item.wxid}`)
  })
  if (!result.length) {
    Message.warning('请至少选择一个要跟发的群成员')
    return false
  }
  const arr = []
  result.forEach((element) => {
    arr.push(`${groupInfo.value.wxid}❤${element.wxid}`)
  })
  memberIds.value = arr
  emit('handleChooseMember', result)
  return true
}

// 清空选择
const clearChoose = () => {
  memberIds.value = []
}

defineExpose({ openMemberModal, openMemberModal2, clearChoose })
</script>
<style scoped>
.custom-radio-card {
  border: 1px solid var(--color-border-2);
  border-radius: 2px;
  white-space: nowrap;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  height: 24px;
  padding: 0 10px;
}

.custom-radio-card-mask {
  height: 12px;
  width: 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
}

.custom-radio-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 2px;
}

.custom-radio-card-title {
  color: var(--color-text-1);
  font-size: 12px;
}

.custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
